package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class jdbcUtilByDruid {
    static DataSource ds;
    static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
    static {
        Properties prop = new Properties();
        try{
            /*prop.load(new FileInputStream("src\\druid.properties"));*/
            prop.load(jdbcUtilByDruid.class.getClassLoader().getResourceAsStream("druid.properties"));
            //创建druid连接池，通过properties的数据
            ds= DruidDataSourceFactory.createDataSource(prop);
        }catch(IOException e){
            throw new RuntimeException(e);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
    //获取连接
    public static Connection getConnection() throws ClassNotFoundException,SQLException,IOException {
        Connection conn=threadLocal.get();
        if(conn==null){
            conn=ds.getConnection();
            threadLocal.set(conn);
        }
        return conn;
    }
    //关闭资源
    public  static void close(ResultSet rs, Statement stmt, Connection conn){
        try {
            if(rs!=null){
                rs.close();
            }
            if(stmt!=null){
                stmt.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
